<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Response;
use App\Models\Advert;
use App\Models\Position;
use App\Models\PositionTranslation;
use App\Services\QiniuServices;
use DB;


class AdvController extends AdminController
{

    public function index()
    {
        return view('admin.ad.index');
    }

    public function data(Request $request)
    {
        $lang = $request->lang??lang();
        $model = PositionTranslation::query();
        $model = $model->where('locale',$lang);
		$keyword=$request->get('title');
        if ($keyword) {
			
            $model = $model->where('title', 'like',"%{$keyword}%")->orWhere('firsttitle', 'like', "%{$keyword}%");
        }


        $res = $model->with('advname')->where('pid','!=',0)->where('type',1)->orderBy('id', 'desc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return response()->json($data);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ad.create', compact('positions'));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createPosition()
    {
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ad.position', compact('positions'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        DB::beginTransaction();
        try {

            $Position = new Position();
            $Position->classname = $request->title;
            //$Position->tag = $request->tag;
            $sid = PositionTranslation::max('sid');
            $Position->status = 1;
            foreach (config('translatable.locales') as $locale => $item) {
                $Position->translateOrNew($locale)->pid = $request->pid??0;
                $Position->translateOrNew($locale)->type = $request->type??1;
                $Position->translateOrNew($locale)->sid = $sid + 1;
                $Position->translateOrNew($locale)->title = $request->title??$request->classname;
                $Position->translateOrNew($locale)->firsttitle = $request->firsttitle;
                $Position->translateOrNew($locale)->secondtitle = $request->secondtitle;
                $Position->translateOrNew($locale)->thirdtitle = $request->title;
                $Position->translateOrNew($locale)->keywords = $request->keywords;
                $Position->translateOrNew($locale)->description = $request->description;
                $Position->translateOrNew($locale)->thumb = $request->thumb;
                $Position->translateOrNew($locale)->body = $request->body;
                $Position->translateOrNew($locale)->remarks = $request->remarks;
                $Position->translateOrNew($locale)->sort = $request->sort??999;
            }
            $Position->save();
            DB::commit();

            return  Response::json(['code' => 0, 'msg' => '添加成功', 'data' => '添加成功', 'url' => route('admin.ad')]);

        } catch (\Exception $exception) {
            DB::rollback();

        }

        return response()->json(['code' => 0, 'msg' => '系统错误']);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function editPosition(Request $request)
    {
        $id = (int)$request->get('id');
        $position = PositionTranslation::with('advname')->findOrFail($id);
        $position = $position->advname;
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ad.positionedit', compact('positions', 'position','id'));
    }



    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request)
    {
        $id = (int)$request->get('id');
        $position = PositionTranslation::with('advname')->findOrFail($id);
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.ad.edit', compact('positions', 'position'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {

            $id = (int)$request->get('id');
            if(empty($id))  return Response::json(['code' => 1, 'msg' => '非法操作']);
            $data = $request->except(['_token', 'file']);
			$request = (object)$data;
            $PositionTranslation = PositionTranslation::findOrFail($id);
            //更新主表
            $Position = Position::whereTranslation('id', $id)->firstOrFail();
			DB::beginTransaction();
			try {
				foreach (config('translatable.locales') as $locale => $item) {
				 
					$Position->translateOrNew($locale)->sid = $PositionTranslation->sid;
					if(!$Position->hasTranslation($locale)){
					  
						$Position = $this->createItem($Position,$request,$locale);
						$Position->save();
					}
					
				}

				$PositionTranslation->update($data);
				DB::commit();
				return response()->json(['code' => 0, 'msg' => '更新成功']);
		   
			} catch (\Exception $exception) {
				DB::rollback();
			}
	   
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,QiniuServices $qiniu)
    {
        $ids = (array)$request->get('ids');
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
		
        DB::beginTransaction();
       //try { 
		
			//删除云端资源
			foreach($ids as $id){
				
				//检查广告位下是否有 广告
				$Position = Position::whereTranslation('id', $id)->firstOrFail();
				 
				if($Position->translations->count()){
					foreach($Position->translations as $obj){
						//删除云端资源
						$qiniu->objFromDelete($obj);
					}
					$Position->deleteTranslations();
				}
				$Position->delete();
			}
		
		
		
		
		
 			
			DB::commit();
			return response()->json(['code' => 0, 'msg' => '删除成功']);
		 
 
		
        //} catch (\Exception $exception) {
            DB::rollback();
       // }

        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }

	private function createItem($Position,$request,$locale){
		
			//新增时此时需要设置
			if(isset($this->sid)) $Position->translateOrNew($locale)->sid = $this->sid + 1;

			$Position->translateOrNew($locale)->pid = $request->pid;
			$Position->translateOrNew($locale)->type = $request->type;
			$Position->translateOrNew($locale)->title = $request->title;
			$Position->translateOrNew($locale)->firsttitle = $request->firsttitle;
			$Position->translateOrNew($locale)->secondtitle = $request->secondtitle;
			$Position->translateOrNew($locale)->thirdtitle = $request->thirdtitle;
			$Position->translateOrNew($locale)->keywords = $request->keywords;
			$Position->translateOrNew($locale)->description = $request->description;
			$Position->translateOrNew($locale)->thumb = $request->thumb;
			$Position->translateOrNew($locale)->body = $request->body;
			$Position->translateOrNew($locale)->remarks = $request->remarks;
			$Position->translateOrNew($locale)->sort = $request->sort??255;
		return $Position;
	}
    /***
	** 获取广告位列表
	**/
    private function getPositionClass(){
      
     return  PositionTranslation::with('advname')->where(['pid'=>0,'type'=>1])->lang()->get();

    }



}
